package com.example.jin.alarmservice;

import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.view.View.OnClickListener;

import java.util.Calendar;

public class alarmService extends AppCompatActivity implements OnClickListener{
    private static alarmService appRef = null;
    private Button btn_alarm, btn_exit;
    boolean k =false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        appRef = this;
        btn_alarm = (Button) findViewById(R.id.alarm);
        btn_alarm.setOnClickListener(this);
        btn_exit = (Button) findViewById(R.id.exit);
        btn_exit.setOnClickListener(this);
    }

    public static alarmService getAppRef(){return appRef;}

    public void btEvent(String data){setTitle(data);}

    @Override
    public void onClick(View arg0) {
        if(arg0 == btn_alarm){
            setTitle("Waiting......Alarm=5");
            Intent intent = new Intent(alarmService.this, alarmReceive.class);
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            //getBroadcast()使PendingIntent扮演一个广播的功能，就像调用 Context.sendBroadcast()函数一样
            PendingIntent p_intent = PendingIntent.getBroadcast(alarmService.this,0,intent,0);

            Calendar calendar = Calendar.getInstance();
            calendar.setTimeInMillis(System.currentTimeMillis());
            calendar.add(Calendar.SECOND, 5);

            AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
            alarmManager.set(AlarmManager.RTC,calendar.getTimeInMillis(),p_intent);
        }

        if(arg0 == btn_exit){
            Intent intent = new Intent(alarmService.this, alarmReceive.class);
            PendingIntent p_intent = PendingIntent.getBroadcast(alarmService.this,0,intent,0);
            AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
            alarmManager.cancel(p_intent);
            finish();
        }
    }
}
